package com.itheima.mode_test;

import org.I0Itec.zkclient.ZkClient;
import org.junit.Test;

/**
 * @author ：yuan_he_song
 */
public class ZkClientTest {

    private ZkClient zkClient;

    private String server = "192.168.244.128:2181";
    // 根节点
    private static final String rootPath = "/heima";
    // 服务节点(在此节点下创建临时序号节点)
    private static final String serverPath = rootPath + "/server";
    // 当前的临时序号节点 /heima/server0000001 /heima/server0000002 ...
    private String nodePath;
    Thread stateThread;

    @Test
    public void init() throws InterruptedException {
        zkClient = new ZkClient(server,5000,10000);
        System.err.println("zookeeper链接成功" + server);
        // 创建根节点
        buildRootNode();
        // 创建临时节点
        createServerNode();
        // 开启一个线程, 定时向zk上报自己的状态
        // stateThread = new Thread(()->{
        //     while (true){
        //         updateServerNode();
        //         try {
        //             Thread.sleep(5000);
        //         } catch (InterruptedException e) {
        //             e.printStackTrace();
        //         }
        //     }
        // },"zk_stateThread");
        // stateThread.setDaemon(true);
        // stateThread.start();
        Thread.sleep(Integer.MAX_VALUE);
    }


    private void updateServerNode() {
        zkClient.writeData(nodePath,"888");
    }

    /** 创建根节点 */
    private void buildRootNode() {
        if (!zkClient.exists(rootPath)){
            zkClient.createPersistent(rootPath);
        }
    }
    /** 创建临时序号节点 */
    private void createServerNode(){
        nodePath = zkClient.createEphemeralSequential(serverPath,"I am coming");
        System.out.println("创建临时序号节点: " + nodePath);
    }

}
